const jwt = require('jsonwebtoken')
const {
    readFileSync
} = require('fs')
const path = require('path')
const respJson = require('../utils/respJson')


module.exports = (req, resp, next) => {
    //规定令牌必须从请求头传来
    if (!req.headers.authorization) {
        respJson(resp, 406, '缺少身份验证！')
        return
    }
    //验证令牌真伪 - 是否能解开
    let configFilePath = path.join(__dirname, '../', 'config', 'config.json')
    let salt = JSON.parse(readFileSync(configFilePath, 'utf-8')).tokenSalt
    jwt.verify(req.headers.authorization, salt, (err, decoded) => {
        if (err) {
            respJson(resp, 407, '身份验证失败！')
            return
        }
        //验证令牌有效期
        let {
            startTime,
            expires
        } = decoded
        if (startTime + expires < +new Date()) {
            respJson(resp, 408, '登录过期！')
            return
        }
        next()
    })
}